﻿using System.Linq;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace TfsBuildExtensions.Activities.TeamFoundationServer
{
    /// <summary>
    /// Contains data for the document abstract
    /// </summary>
    internal class DocumentAbstract
    {
        internal string Developers { get; private set; }
        internal int NumberOfChangesets { get; private set; }
        internal int ChangesetPeriodInDays { get; private set; }
        internal int BuildPeriodInDays { get; private set; }
        internal int NumberOfWorkItems { get; private set; }
        internal string WorkItemCreators { get; private set; }
        internal int TotalNumberOfChanges { get; private set; }

        internal DocumentAbstract(IBuildDetail currentBuild, IBuildDetail previousBuild, Changeset[] changesets, WorkItem[] workItems)
        {
            Developers = "N/A";
            if (changesets.Length > 0)
            {
                this.NumberOfChangesets = changesets.Length;
                Developers = string.Join(",", (from p in changesets
                                               where !string.IsNullOrWhiteSpace(p.Committer)
                                               select p.Committer).Distinct().Take(5).ToArray());
                if (changesets[0].CreationDate > changesets[changesets.Length - 1].CreationDate)
                {
                    this.ChangesetPeriodInDays = (int)(changesets[0].CreationDate - changesets[changesets.Length - 1].CreationDate).TotalDays;
                }
                else
                {
                    this.ChangesetPeriodInDays = (int)(changesets[changesets.Length - 1].CreationDate - changesets[0].CreationDate).TotalDays;
                }
            }

            BuildPeriodInDays = (int)(currentBuild.FinishTime - previousBuild.FinishTime).TotalDays;
            if (workItems.Length > 0)
            {
                this.NumberOfWorkItems = workItems.Length;
                WorkItemCreators = string.Join(",", (from p in workItems
                                                       where !string.IsNullOrWhiteSpace(p.CreatedBy)
                                               select p.CreatedBy).Distinct().Take(5).ToArray());
            }
            TotalNumberOfChanges = (from p in changesets
                                    select p.Changes.Count()).Sum();
        }
    }
}